//1
///========依赖引入=======///
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');//使用session需要单独包含此模块
///========依赖引入=======///

///========服务端链接数据库=======///
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/share')
///========服务端链接数据库=======///

//2(1、2、5)
///=======路由信息 （接口地址）开始 存放在./routes目录下===========//

var index = require('./routes/index');//home接口
var message = require('./routes/message');//信息接口
var upload = require('./routes/upload');
var user = require('./routes/user')//用户接口
// var city = reqiure('./routes/city')// 城市接口
var critiques = require('./routes/critiques');//发表评论接口
var join = require('./routes/join');//发布参与活动接口

///=======路由信息 （接口地址）开始 存放在./routes目录下===========//

var app = express();

//3
///=======模板引擎开始========//
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
///=======模板引擎结束=======//

//4
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret:'1',
  name:'session_id',
  cookie:{maxAge:600000},//cookie 储存毫秒
  resave:false,
  saveUninitialized:true//无论是否有session cookie，每次请求都设置session cookie


}))//保存数据中间件，需要在cookie后挂载

app.use(express.static(path.join(__dirname, 'public')));

//5
///=======路由信息 （接口地址）介绍；注册各个接口===========//
app.use('/', index);//在app中注册index该接口 
app.use('/api',message);//在app中注册message接口
app.use('/api',upload);//在app中注册upload接口
app.use('/api',user)//在app中注册user接口
app.use('/api',critiques);//在app中注册critiques接口
app.use('/api',join);//在app中注册join接口
// app.use('/api',city);// 在app中注册城市接口
///
///=======路由信息 （接口地址）介绍；注册各个接口===========//

//6
///======重定向=========///
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
///======重定向=========///

//7
///======定义端口=========///
app.listen(3000,()=>{
    console.log('listening on port 3000')
})
///======定义端口=========///

//8
module.exports = app;